import React, { PropsWithChildren, useRef } from 'react';
import { Form, Input, Button, message, FormInstance } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import * as actions from '../../../../store/actions/login'
import { register } from '../../../../api/login';
import { encryption, getResponseData } from '../../../../utils/helpers';
import { RegisterProps, BaseResponse } from '../../../../api/types';
const tailLayout = {
    wrapperCol: { offset: 0, span: 16 },
};

type exactProps = { codeUrl: string, refreshCode: (n: number) => void }
// 获取导出的所有actions的类型即得到属性值
type RegisterFormProps = typeof actions & exactProps
type Props = PropsWithChildren<RegisterFormProps>
const RegisterForm = (props: Props) => {
    // 校验通过， 注册
    const onFinish = async (values: RegisterProps) => {
        // 先加密，然后发送请求，格式化数据
        const res = getResponseData<BaseResponse>(await register(encryption(values) as RegisterProps));
        if (res.code === 1) {
            message.success(res.msg + ", 去登录吧!");
            // 重置表单值
            ref.current?.resetFields();
            // 重置验证码
            props.refreshCode(Math.random());
            // 跳到登录页
            props.changeTransform(true);
        } else {
            message.error(res.msg);
        }
    };
    // 当验证失败时
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    // form的实例
    const ref = useRef<FormInstance>(null)
    return (
        <Form
            name="basic"
            ref={ref}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            id="registerForm"
        >
            <Form.Item
                name="username"
                rules={[{ required: true, message: '请输入用户名!' }]}

            >
                <Input id="registerUsername" placeholder="请输入用户名" prefix={<UserOutlined className="site-form-item-icon" />} />
            </Form.Item>

            <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
            >
                <Input.Password id="registerPassword" placeholder="请输入密码" prefix={<LockOutlined className="site-form-item-icon" />} />
            </Form.Item>
            <Form.Item
                name="repassword"
                rules={[{ required: true, message: '请再次输入密码!' }, ({ getFieldValue }) => ({
                    validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                            return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次密码不匹配'));
                    },
                }),]}
                dependencies={['password']}
            >
                <Input.Password placeholder="请再次输入密码" prefix={<LockOutlined className="site-form-item-icon" />} />
            </Form.Item>
            <Form.Item name='code' rules={[{ required: true, message: '请输入验证码' }]}>
                <div className='wrap fx-h-c'>
                    <Input style={{ width: '14rem' }} placeholder='请输入验证码'></Input>
                    <div dangerouslySetInnerHTML={{ __html: props.codeUrl }} className='cs' onClick={() => props.refreshCode(Math.random())} ></div>
                </div>
            </Form.Item>
            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" className='btn'>
                    注册
        </Button>
            </Form.Item>
            {/* 切换到登录 */}
            <span className='cs cm-color to-register' onClick={() => { props.changeTransform(true);/*跳转到登录页 */ }}>已经注册，点此去登录!</span>
        </Form>
    );
};

export default connect(() => ({}), actions)(RegisterForm);